<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总记录数：{{ total }}条</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
              <el-button :loading="downloadLoading" type="danger" size="small" @click="DCexcel">导出excel</el-button>
              <el-button type="primary" size="small" @click.native="showDialogs = true">新增员工</el-button>
            </template>
          </PageTools>
        </div>
        <div>
          <!-- table列表 -->
          <el-table border :data="list">
            <el-table-column type="index" label="序号" />
            <el-table-column prop="username" label="姓名" />
            <el-table-column
              prop="workNumber"
              label="工号"
              :default-sort="{ prop: 'workNumber', order: 'descending' }"
            />
            <el-table-column label="聘用形式">
              <template #default="{ row }">
                {{ convertDate(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" />
            <el-table-column label="入职时间" sortable>
              <template #default="{ row }">
                {{ formatDate(row.timeOfEntry) }}
              </template>
            </el-table-column>
            <el-table-column label="账户状态">
              <el-switch v-model="qy" />
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">
                  查看
                </el-button>
                <el-button type="text" size="small">分配角色</el-button>
                <el-button type="text" size="small" @click.native="delUser(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row type="flex" justify="center" align="middle" style="height: 60px">
            <el-pagination
              background
              :page-sizes="[2, 10]"
              :page-size="query.size"
              layout="sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </div>
      </el-card>
    </div>
    <!-- <AddEmployee :show-dialog.sync="showDialogs" @Refresh="getUesr()" /> -->
    <AddEmployee :show-dialog.sync="showDialogs" />
  </div>
</template>
<script>
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import dictionary from '@/api/constant/employees.js'
import AddEmployee from './components/add-employee.vue'
import dayjs from 'dayjs'
export default {
  components: {
    AddEmployee
  },
  data() {
    return {
      downloadLoading: false,
      qy: true,
      query: {
        page: 1, // 当前页,
        size: 10 // 每页条数
      },
      total: null, // 总数居
      list: [],
      showDialogs: null
    }
  },
  created() {
    this.getUesr()
  },
  methods: {
    // 到处excel
    async DCexcel() {
      this.downloadLoading = true
      // import() 什么时候正式要使用导出功能了,插件才会被正式引入到应用里=>需要script-loader支持
      const excel = await import('@/utils/Export2Excel')
      const { header, parentArray } = this.provideDate()
      // const header = ['姓名', '性别', '年龄', '名望']
      // const data = parentArray
      excel.export_json_to_excel({
        header, // 表头
        data: parentArray, // 表格数据
        filename: `这是第${this.query.page}页的员工数据`, // 文件名字
        autoWidth: true, // 是否自适应宽度
        bookType: 'xlsx' // 输出文件类型
      })
      this.downloadLoading = false
    },
    // 导出数据处理
    provideDate() {
      const map = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        工号: 'workNumber',
        转正日期: 'correctionTime',
        部门: 'departmentName'
      }
      const header = Object.keys(map)
      const value = Object.values(map)
      // 定义[ [ ] ]大数组
      const parentArray = []
      this.list.forEach(item => {
        const childrenArray = []
        for (const key in item) {
          if (value.includes(key)) {
            // 修改后台时间格式
            if (key === 'timeOfEntry' || key === 'correctionTime') {
              item[key] = this.formatDate(item[key])
            }
            // 修改聘用形式
            if (key === 'formOfEmployment') {
              item[key] = this.convertDate(item[key])
            }
            childrenArray.push(item[key])
          }
        }
        parentArray.push(childrenArray)
      })
      return { header, parentArray }
    },
    // 修改时间
    // str='默认值' str如果不传 读取默认值'YYYY-MM-DD'
    formatDate(value, str = 'YYYY-MM-DD') {
      return dayjs(value).format(str)
    },
    // 删除
    async delUser(val) {
      try {
        await this.$confirm('你是否要删除？')
        await delEmployee(val)
        // 解决删除最后一页数据页码正确，数据显示错误问题
        const newPage = Math.ceil((this.total - 1) / this.query.size) // 总页数
        if (this.query.page > newPage) {
          // 不正确修复，重新赋值
          this.query.page = newPage
        }
        this.$message.success('删除成功')
        this.getUesr()
      } catch (error) {
        console.log(error)
      }
    },
    convertDate(type) {
      const map = {}
      dictionary.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.getUesr()
    },
    handleSizeChange(val) {
      this.query.size = val
      this.getUesr()
    },
    async getUesr() {
      const { rows, total } = await getEmployeeList(this.query)
      console.log(rows)
      this.list = rows
      this.total = total
    }
  }
}
</script>
